package grade.dao;

import java.sql.ResultSet;

import org.apache.commons.lang.StringUtils;

import database.DBUtil;
import grade.model.Grade;
import util.Page;

public class GradeDao {
	private static GradeDao dao = null;
	private GradeDao(){
		
	}
	//单例模式，懒加载
	public static GradeDao getInstance(){
		if(null == dao){
			dao = new GradeDao();
		}
		return dao;
	}
	/**
	 * 加载数据
	 * @param page
	 * @param grade
	 * @return
	 * @throws Exception 
	 */
	public ResultSet list(Page page,Grade grade) throws Exception{
		String sql = "select * from grade";
		if(null != grade&&!StringUtils.isEmpty(grade.getName())){
			sql += " where name like '%"+grade.getName()+"%'";
		}
		if(null != page && 0 != page.getPageNum() && 0 != page.getPageSize()){
			sql += " limit "+(page.getPageNum()-1)*page.getPageSize()+","+page.getPageSize();
		}
		return DBUtil.executeQuery(sql);
	}
	/**
	 * 保存数据：新增、编辑
	 * @param grade
	 * @return
	 * @throws Exception 
	 */
	public boolean save(Grade grade) throws Exception{
		int id = grade.getId();
		String sql ;
		if(id == 0){//新增
			sql = "insert into grade values(null,'"+grade.getName()+"','"+grade.getDescc()+"')";
		}else{//编辑
			sql = "update grade set name='"+grade.getName()+"',Descc='"+grade.getDescc()+"' where id='"+grade.getId()+"'";
		}
		DBUtil.execute(sql);//返回的是resultset对象，flag为true；返回的是更新的记录数或没有返回，flag为false
		return true;
	}
	public int delete(String ids) throws Exception{
		int delNum = 0;
		if(!StringUtils.isEmpty(ids)){
			String id[] = ids.split(",");
			ids = ids.replaceAll(",", "','");
			String sql = "delete from grade where id in('"+ids+"')";
			DBUtil.execute(sql);
			delNum = id.length;
		}
		return delNum;
	}
	//获取数据总数
	public int getCount(Grade grade) throws Exception {
		// TODO Auto-generated method stub
		String sql = "select count(*) from grade";
		if(null != grade&&!StringUtils.isEmpty(grade.getName())){
			sql += " where name like '%"+grade.getName()+"%'";
		}
		ResultSet rst = DBUtil.executeQuery(sql);
		int total = 0;
		while(rst.next()){
			total = rst.getInt(1);
		}
		return total;
	}
}
